package com.lwl.blue.commont.utils;

import com.lwl.blue.entity.Users;
import lombok.Data;
import lombok.ToString;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * </p>
 *
 * @version V0.0.1
 * @date 2020/3/18
 */
@Data
@ToString
public class CurrentUser implements Serializable {
    private static final long serialVersionUID = 931937842490178146L;

    public final static String X_CLIENT_TOKEN_USER = "x-client-token-user";

    private static ThreadLocal<Users> userInfoThreadLocal = new ThreadLocal<>();

    public static void setUserInfo(Users userInfo) {
        userInfoThreadLocal.set(userInfo);
    }

    protected static void clear() {
        userInfoThreadLocal.remove();
    }

    /**
     * 当前用户id
     *
     * @return int
     */
    public static Long getUserId() {
        Users userInfo = getUserInfo();
        if (userInfo == null) {
            return null;
        }
        return userInfo.getId();
    }

    /**
     * 当前用户
     *
     * @return UserInfo
     */
    public static Users getUserInfo() {
        Users userInfo = userInfoThreadLocal.get();
        if (userInfo == null) {
            // 默认信息请勿更改！
            userInfo = new Users();
//            userInfo.setRoleId(1L);
            userInfo.setId(110L);
            userInfo.setUserName("配券助手");
        } else {
            try {
                userInfo.setUserName(URLDecoder.decode(userInfo.getUserName(), StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        return userInfo;
    }

}

